<template>
    <div>
        <index-header></index-header>
        <el-container style="width:1000px;height:auto;margin:0 auto;background:#FFFFFF;padding-bottom:100px;">
            <div>
                <div style="width:1000px;height:300px;">
                    <div class="Info">
                        <div class="Info-img">
                            <img style="width:100%;height:100%;" :src="Info.userpic" />
                        </div>
                        <div>
                            <h3>{{ Info.name }}</h3>
                        </div>
                    </div>
                    <div class="Info-right-div">
                        <h4 class="Info-title">账号信息 <el-icon @click="updateUser" style="color:#409EFF;">
                                <Edit />
                            </el-icon></h4>
                        <ul class="Info-info">
                            <li style="display:none;">{{ Info.id }}</li>
                            <li>电话：{{ Info.phone }} </li>
                            <li>邮箱：{{ Info.email }}</li>
                            <li>密码：********** </li>
                            <li>性别：{{ Info.sex }}</li>
                            <li>注册时间：{{ Info.createdtime }}</li>
                            <li>上次修改：{{ Info.updatedtime }}</li>
                        </ul>
                    </div>
                </div>

                <div style="width:1000px;height:auto;">
                    <el-divider />
                    <div class="Address-title">
                        <h3>地址管理</h3>
                        <el-button class="add-icon" @click="addA" type="primary" size="small">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-button>
                    </div>
                    <el-empty v-if="AddressList.length === 0" description="您还没添加地址哦" />
                    <div v-else-if="AddressList.length !== 0" style="width:100%;height:auto;">

                        <el-table :data="AddressList" style="width: 90%;" class="tab"
                            :default-sort="{ prop: 'isDefault', order: 'ascending' }" stripe>
                            <el-table-column prop="consigneeName" label="收件人" width="80" />
                            <el-table-column prop="consigneePhone" label="电话" width="120" />
                            <el-table-column prop="provinces" label="省份" width="100" />
                            <el-table-column prop="city" label="城市" width="100" />
                            <el-table-column prop="county" label="区县" width="100" />
                            <el-table-column prop="detailAddress" label="详细地址" />
                            <el-table-column label="默认地址" width="90" prop="isDefault">
                                <template v-slot:default="scope">
                                    <el-tag class="ml-2" :type="scope.row.isDefault == 1 ? 'success' : 'info'">
                                        {{ scope.row.isDefault == 1 ? "默认" : "普通" }}
                                    </el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" width="100">
                                <template #default="scope">
                                    <el-button link type="primary" size="small" @click="updateAddress(scope.row)">
                                        <el-icon>
                                            <EditPen />
                                        </el-icon>
                                    </el-button>
                                    <el-button link type="danger" size="small"
                                        @click="deleteAddress(scope.row.addressId)">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
            <!--    更新用户信息-->
            <el-dialog v-model="dialogFormVisibleOfUpdate" title="编辑地址信息">
                <el-form ref="AddressForm" :model="AddressFormData" :rules="rules">
                    <!--      表单验证-->
                    <el-form-item label="收件人" prop="consigneeName">
                        <el-input v-model="AddressFormData.consigneeName" placeholder="请输入收件人姓名" />
                    </el-form-item>
                    <el-form-item label="手机号" prop="consigneePhone">
                        <el-input v-model="AddressFormData.consigneePhone" placeholder="请输入收件人手机号" />
                    </el-form-item>
                    <el-form-item label="省市区" prop="county">
                        <el-cascader size="large" :options="options" v-model="selectedOptions" @change="handleChange"
                            filterable placeholder="请选择省市区" clearable>
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="详细地址" prop="detailAddress">
                        <el-input type="textarea" v-model="AddressFormData.detailAddress" placeholder="请输入详细地址" />
                    </el-form-item>
                    <el-form-item label="默认地址">
                        <div class="mb-2 flex items-center text-sm">
                            <el-radio-group v-model="AddressFormData.isDefault" class="ml-4">
                                <el-radio :label="1" size="large">默认</el-radio>
                                <el-radio :label="0" size="large">普通</el-radio>
                            </el-radio-group>
                        </div>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="flex-u">
                        <el-button type="primary" @click="submitFormUpdateData(AddressForm)">确定</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 添加地址 -->

            <el-dialog v-model="dialogFormVisibleOfAdd" title="添加地址信息">
                <el-form ref="AddressForm" :model="AddFormData" :rules="rule2">
                    <!--      表单验证-->
                    <el-form-item label="收件人" prop="consigneeName">
                        <el-input v-model="AddFormData.consigneeName" placeholder="请输入收件人姓名" />
                    </el-form-item>
                    <el-form-item label="手机号" prop="consigneePhone">
                        <el-input v-model="AddFormData.consigneePhone" placeholder="请输入收件人手机号" />
                    </el-form-item>
                    <el-form-item label="省市区" prop="county">
                        <el-cascader size="large" :options="options" v-model="selectedOptions"
                            @change="handleChangeOfAdd" filterable placeholder="请选择省市区" clearable>
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="详细地址" prop="detailAddress">
                        <el-input type="textarea" v-model="AddFormData.detailAddress" placeholder="请输入详细地址" />
                    </el-form-item>
                    <el-form-item label="默认地址" prop="isDefault">
                        <div class="mb-2 flex items-center text-sm">
                            <el-radio-group v-model="AddFormData.isDefault" class="ml-4">
                                <el-radio :label="1" size="large">默认</el-radio>
                                <el-radio :label="0" size="large">普通</el-radio>
                            </el-radio-group>
                        </div>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="flex-u">
                        <el-button type="primary" @click="addAdress(AddressForm)">确定</el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 用户修改信息 -->
            <el-dialog v-model="dialogFormVisibleOfUser" title="修改用户信息">
                <el-form ref="userForm" :model="userData" :rules="userRule">

                    <el-form-item label="账号" prop="phone">
                        <el-input v-model="userData.phone" disabled />
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="userData.name" />
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userData.email" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="userData.password" />
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <input type="radio" name="radios" value="男" v-model="userData.sex"><label>男</label>
                        <input type="radio" name="radios" value="女" v-model="userData.sex"><label>女</label>
                    </el-form-item>
                    <el-form-item label="头像" prop="userpic">
                        <to-up-load @send="upreceive"></to-up-load>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="flex-u">
                        <el-button type="primary" @click="changeUserInfo(userForm)">确定</el-button>
                    </div>
                </template>
            </el-dialog>

        </el-container>
    </div>
</template>
    
<script>
import { toRefs, reactive, ref } from '@vue/reactivity'
// import { useRoute } from "vue-router"
import indexHeader from './indexHeader.vue'
//引用 element-china-area-data
import { regionData, CodeToText } from 'element-china-area-data'
import { AddressApi, delAddressApi, updateAddressApi, addAddressApi, UpdateUserApi } from "../utils/clientApi"
import { ElMessage } from 'element-plus'
import ToUpLoad from './toUpLoad.vue'

export default {
    components: { indexHeader, ToUpLoad },
    name: "mySelf",
    setup() {
        // const route = useRoute()
        const data = reactive({
            param: "男",
            props: {
                multiple: true,
            },
            options: regionData,//选择格式
            selectedOptions: [], //省市区绑定数组
            AddressList: [],
            Info: {},
            dialogFormVisibleOfUpdate: false,
            AddressFormData: {
                addressId: "",
                city: "",
                consigneeName: "",
                consigneePhone: "",
                county: "",
                detailAddress: "",
                isDefault: 0,
                provinces: "",
                userId: "",
            },
            rules: {
                consigneePhone: [{ required: true, message: "请正确填写手机号", pattern: /^[1][34578][0-9]{9}$/, trigger: 'blur' },],
                consigneeName: [{ required: true, message: "必填项", trigger: 'blur' },],
                detailAddress: [{ required: true, message: "必填项", trigger: 'blur' }],
                county: [{ required: true, message: '请选择地址', trigger: 'change' }],
            },
            // 添加
            dialogFormVisibleOfAdd: false,
            AddFormData: {
                addressId: "",
                city: "",
                consigneeName: "",
                consigneePhone: "",
                county: "",
                detailAddress: "",
                isDefault: 0,
                provinces: "",
                userId: "",
            },
            rule2: {
                consigneePhone: [{ required: true, message: "请正确填写手机号", pattern: /^[1][34578][0-9]{9}$/, trigger: 'blur' },],
                consigneeName: [{ required: true, message: "必填项", trigger: 'blur' },],
                detailAddress: [{ required: true, message: "必填项", trigger: 'blur' }],
                county: [{ required: true, message: '请选择地址', trigger: 'change' }],
            },
            // 修改用户信息
            dialogFormVisibleOfUser: false,
            userData: {
                id: "",
                name: "",
                sex: "",
                email: "",
                phone: "",
                password: "",
                userpic: "",
                updatedtime: ""
            },
            userRule: {
                email: [{ required: true, message: "必填项", trigger: 'blur' }],
                name: [{ required: true, message: "必填项", trigger: 'blur' }],
                password: [{ required: true, message: "必填项", trigger: 'blur' }],
                sex: [{ required: true, message: "必填项", trigger: 'blur' }],
                phone: [{ required: true, message: "必填项", trigger: 'blur' }],

            }

        })
        data.Info = JSON.parse(localStorage.getItem("userInfo"))
        // 获取用户地址列表
        const getAddressList = () => {
            const id = JSON.parse(localStorage.getItem("userInfo")).id
            AddressApi(id).then(res => {
                if(res.status === 200){
                    data.AddressList = res.data
                }else{
                    data.AddressList=0
                }
               
                // console.log(res);
            })
        }
        getAddressList()
        // 删除
        const deleteAddress = (id) => {
            delAddressApi(id).then(res => {
                if (res.status === 200) {
                    getAddressList()
                    ElMessage.error(res.msg)
                } else {
                    ElMessage.success(res.msg)
                }
            })
        }
        const selectedOptions = ref([])
        // 解构赋值、修改地址信息
        // 
        const updateAddress = (row) => {
            data.dialogFormVisibleOfUpdate = true
            const { addressId, city, consigneeName, consigneePhone, county, detailAddress, isDefault, provinces, userId } = row
            data.AddressFormData.addressId = row.addressId
            data.AddressFormData.consigneeName = row.consigneeName
            data.AddressFormData.consigneePhone = row.consigneePhone
            data.AddressFormData.detailAddress = row.detailAddress
            data.AddressFormData.isDefault = row.isDefault
            data.AddressFormData.userId = row.userId
        }
        // 修改地址赋值给表单
        const handleChange = (label) => {
            if (selectedOptions.value[0] != null && selectedOptions.value[1] != null && selectedOptions.value[2] != null) {
                const str = CodeToText[selectedOptions.value[0]] + '/' + CodeToText[selectedOptions.value[1]] + '/' + CodeToText[selectedOptions.value[2]]
                data.AddressFormData.provinces = CodeToText[selectedOptions.value[0]]
                data.AddressFormData.city = CodeToText[selectedOptions.value[1]]
                data.AddressFormData.county = CodeToText[selectedOptions.value[2]]
            }
        }

        const AddressForm = ref()
        // 提交修改
        const submitFormUpdateData = (EForm) => {
            let _data = data
            EForm.validate(res => {
                if (!res) {
                    //表单验证不通过不做任何改变
                    ElMessage.error("请正确填写信息")
                    return;
                } else {
                    // console.log(_data.AddressFormData)
                    updateAddressApi(JSON.stringify(_data.AddressFormData)).then(res => {
                        if (res.status === 200) {
                            data.dialogFormVisibleOfUpdate = false
                            ElMessage.success(res.msg)
                            getAddressList()
                        } else {
                            ccess(res.msg)
                        }
                    })
                }
            }
            )
        }

        // 添加地址
        const AddAddressForm = ref()

        const addA=()=>{
            data.dialogFormVisibleOfAdd = true
        }
        const handleChangeOfAdd = (label) => {
            if (selectedOptions.value[0] != null && selectedOptions.value[1] != null && selectedOptions.value[2] != null) {
                // const str = CodeToText[selectedOptions.value[0]] + '/' + CodeToText[selectedOptions.value[1]] + '/' + CodeToText[selectedOptions.value[2]]
                data.AddFormData.provinces = CodeToText[selectedOptions.value[0]]
                data.AddFormData.city = CodeToText[selectedOptions.value[1]]
                data.AddFormData.county = CodeToText[selectedOptions.value[2]]
                data.AddFormData.userId = JSON.parse(localStorage.getItem("userInfo")).id
            }
        }
        const addAdress = (EForm1) => {
            let _data = data
            EForm1.validate(res => {
                if (!res) {
                    //表单验证不通过不做任何改变
                    ElMessage.error("请正确填写信息")
                    return;
                } else {
                    addAddressApi(JSON.stringify(_data.AddFormData)).then(res => {
                        if (res.status === 200) {
                            data.dialogFormVisibleOfAdd = false
                            ElMessage.success(res.msg)
                            getAddressList()
                        } else {
                            ElMessage.success(res.msg)
                        }
                    })
                }
            })
        }

        // 图片上传
        const upreceive = (url) => {
            //暂时存储到localStorage
            if (url !== "") {
                ElMessage.success("图片上传成功")
                sessionStorage.setItem("tempPic", url)
                data.userData.userpic = sessionStorage.getItem("tempPic")
            }else{
                ElMessage.error("图片上传失败")
            }
        }
        // 解构赋值
        const userForm = ref()
        const updateUser = () => {
            const user = JSON.parse(localStorage.getItem("userInfo"))
            data.dialogFormVisibleOfUser = true
            data.userData = user

        }
        // 提交修改用户信息
        const changeUserInfo = (EForm2) => {
            let _data = data
            EForm2.validate(res => {
                if (!res) {
                    //表单验证不通过不做任何改变
                    ElMessage.error("请正确填写信息")
                    return;
                } else {
                  
                    // localStorage.setItem("userInfo", JSON.stringify(_data.userData))
                    UpdateUserApi(JSON.stringify(_data.userData)).then(res => {
                        if (res.status === 200) {
                            window.location.reload()
                            data.dialogFormVisibleOfUser = false
                            ElMessage.success(res.msg)
                            console.log(_data.userData);

                        } else {
                            ElMessage.success(res.msg)
                        }
                    })
                }
            })

        }

        return {
            ...toRefs(data),
            getAddressList, deleteAddress, updateAddress, AddressForm, changeUserInfo, userForm, updateUser,
            selectedOptions, handleChange, submitFormUpdateData, addAdress, AddAddressForm, handleChangeOfAdd,
            upreceive,addA
        }
    }
}
</script>
    
<style scope>
.Info {
    width: 200px;
    height: 300px;
    display: block;
    float: left;
    text-align: center;
}

.Info-img {
    width: 160px;
    height: 160px;
    margin: 0 auto;
    margin-top: 30px;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 20px;

}

.Info-right-div {
    width: 600px;
    height: 300px;
    margin-left: 70px;
    display: block;
    float: left;
}

.Info-title {
    text-align: left;
}

.Info-info>li {
    margin-top: 10px;
    display: block;
    text-align: left;
    line-height: 26px;
    font-size: 17px;
}

.Address-title {
    width: 1000px;
    height: 60px;
}

.Address-title>h3 {
    display: block;
    float: left;
    line-height: 0px;
    position: relative;
    top: 10px;
    left: 30px;
}

.add-icon {
    float: right;
    position: relative;
    right: 30px;
    top: 17px;
}

.tab {
    margin: 0 auto;
}
</style>